import React, { Component } from 'react';
import Cm from "./extendCodeMirror.js";  // 代码在文章底部, 用于初始化编辑器的格式化代码的功能
import { UnControlled as CodeMirror } from 'react-codemirror2'
import "codemirror/lib/codemirror.js"
import "codemirror/lib/codemirror.css"
//引入编辑语言  xml
import "codemirror/mode/xml/xml"
// 引入JavaScript
import "codemirror/mode/htmlmixed/htmlmixed"
import "codemirror/mode/htmlembedded/htmlembedded"
import 'codemirror/mode/javascript/javascript'
// 引入背景主题
import "codemirror/theme/yonce.css"
import "codemirror/theme/dracula.css"
import "codemirror/theme/seti.css"
//代码高亮
import 'codemirror/addon/selection/active-line';
// 代码折叠
import 'codemirror/addon/fold/foldgutter.css';
import 'codemirror/addon/fold/foldcode.js';
import 'codemirror/addon/fold/foldgutter.js';
import 'codemirror/addon/fold/brace-fold.js';
import 'codemirror/addon/fold/comment-fold.js';
import 'codemirror/addon/fold/xml-fold.js';
import 'codemirror/addon/fold/indent-fold.js';
import 'codemirror/addon/fold/markdown-fold.js';
//代码滚动
import 'codemirror/addon/scroll/simplescrollbars.js'
import 'codemirror/addon/scroll/simplescrollbars.css'
import 'codemirror/addon/edit/closebrackets.js';
import 'codemirror/addon/edit/closetag.js';
import 'codemirror/keymap/sublime.js';
import 'codemirror/addon/hint/show-hint.css';
import 'codemirror/addon/hint/show-hint.js';
import 'codemirror/addon/hint/css-hint.js';
import 'codemirror/addon/hint/html-hint.js';
import 'codemirror/addon/hint/javascript-hint.js';
//声明JSHINT
// const jshint = require("./jshint"); // jshit.js 在文章底部
// (window as any).JSHINT = jshint.JSHINT;
//初始化模板
const template = {
	html: `<!DOCTYPE html>
	<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Document</title>
	</head>
	<body>
	<div></div>
	<script>
	
	</script>
	</body>
	</html>`,
	css: `*{
		margin:0;
		padding:0;
	}`
}

interface htmlProps {
	mode: string
	type: string
}
interface htmlState {
}
let changeTimer;

/**代码编译器 */
class CodeCustom extends Component<htmlProps, htmlState> {

	editor: any;
	constructor(props?) {
		super(props)
		this.state = {

		}
	}

	componentDidMount(): void {

	}
	// 代码提示
	synonyms = (cm, option) => {
		let comp = [
			"要提示的代码1",
			"要提示的代码2",
			"..."
		]
		return new Promise(function (accept) {
			setTimeout(function () {
				var cursor = cm.getCursor(), line = cm.getLine(cursor.line);
				var start = cursor.ch, end = cursor.ch;
				while (start && /[a-zA-Z0-9_.]/.test(line.charAt(start - 1))) --start;
				while (end < line.length && /[a-zA-Z0-9_.]/.test(line.charAt(end))) ++end;
				var word = line.slice(start, end);
				var result_comp = [];
				for (let i = 0; i < comp.length; i++) {
					if (comp[i].indexOf(word) !== -1) {
						result_comp.push(comp[i]);
					}
				}
				if (result_comp.length) {
					return accept({
						list: result_comp,
						from: Cm.Pos(cursor.line, start),
						to: Cm.Pos(cursor.line, end)
					});
				} else {
					return accept(null)
				}
			}, 50)
		})
	}

	/**
 * 获取html文件的内容
 */
	getCodeRun = (url, id) => {
		var rq = new XMLHttpRequest();
		rq.open('GET', url, false);
		rq.overrideMimeType('text/html;charset=utf-8')
		rq.send(null);

		const ifr: any = document.getElementById(id)
		const ifrdoc = ifr.contentWindow.document
		ifrdoc.open()
		ifrdoc.write(rq.responseText)
		ifrdoc.close()
	}

	// codemirror的生命周期
	onEditorDidMount = editor => {
		this.editor = editor;
		console.log(editor);
		// editor.setSize("width", 'height'); // 设置编辑器宽高
		// 绑定其他快捷键, 这里以按下ctrl- 格式化编辑器代码做示例
		editor.addKeyMap({
			'Ctrl-B': this.autoFormatSelection,
		})
	}

	// 格式化
	autoFormatSelection = () => {
		const script_length = this.editor.getValue().length;
		const startPos = { line: 0, ch: 0, sticky: null };
		const endPos = this.editor.doc.posFromIndex(script_length);
		this.editor.setSelection(startPos, endPos);
		this.editor.autoFormatRange(startPos, endPos);
		this.editor.commentRange(false, startPos, endPos);
	}

	codeChange = (editor, data, value) => {
		clearTimeout(changeTimer)
		changeTimer = null
		if (!changeTimer) {
			changeTimer = setTimeout(() => {
				// console.log(value);
			}, 2000)
		}
	}

	setValue = (value) => {
		return this.editor.setValue(value)
	}

	//获取代码
	getValue = () => {
		return this.editor.getValue()
	}

	//运行代码
	codeRun = (id) => {
		const dom: any = document.getElementById(id)
		const word = dom.contentWindow.document
		const value = this.getValue()
		word.open()
		word.write(value)
		word.close()
	}


	render() {
		const { mode, type } = this.props
		return (
			<CodeMirror
				className="MirrorSelf"
				editorDidMount={this.onEditorDidMount}
				value={template[type]}
				onChange={this.codeChange}
				options={{
					extraKeys: {                    //配置按键
						"Alt": "autocomplete",      // 按下`alt`时出现代码提示
					},
					matchBrackets: true,            // 匹配括号
					hintOptions: { hint: this.synonyms },  // 自动提示配置
					lineNumbers: true, 		//显示行号
					mode: { name: mode },		//语言
					autofocus: true,		//自动获取焦点
					styleActiveLine: true,		//光标代码高亮
					theme: 'dracula',  	//主题
					scrollbarStyle: 'overlay',
					lineWrapping: true, //代码自动换行
					indentUnit: 2,       // 缩进配置（默认为2）
					foldGutter: true,
					lint: false,		//代码出错提示
					gutters: ['CodeMirror-linenumbers', 'CodeMirrorfoldgutter', "CodeMirror-lint-markers"],//end
				}}
			/>
		)
	}
}

export default CodeCustom;